package com.yy.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yy.ant.sys.entity.Log;
import com.yy.ant.sys.entity.User;
import com.yy.ant.sys.service.ILogService;
import com.yy.ant.sys.service.IUserService;
import com.yy.model.ResultMsg;
import com.yy.utils.JwtUtils;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Component
public class TokenInterceptor implements HandlerInterceptor {



    @Autowired
    private ILogService iLogService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        System.out.println("token:"+token);
        response.setCharacterEncoding("utf-8");
        if(token != null){
            ResultMsg result = JwtUtils.validateJWT(token);
            //写入用户日志
            Claims claims= (Claims) result.getData();
            if (StringUtils.isNotBlank(claims.getId())){
                Log log=new Log();
                log.setUserid(Long.valueOf(claims.getId()));
                log.setName(claims.getSubject());
                log.setIp(getIpAddr(request));
                // 获取request
                HttpServletRequest requests = getHttpServletRequest();
                try {
                    // 获取所有参数方法一：
                    Enumeration<String> enu = requests.getParameterNames();
                    String name="";
                    while (enu.hasMoreElements()) {
                        String paraName = enu.nextElement();
                        name +=paraName + ": " + requests.getParameter(paraName)+",";
                    }
                    // 获取请求的参数
                    log.setParameter(name);
                    //logger.info("ARGS:" +name);     // 方法本传了哪些参数
                } catch (Exception e) { }
                try{
                    String Agent=request.getHeader("User-Agent");
                    UserAgent userAgent = UserAgent.parseUserAgentString(Agent);
                    Browser browser = userAgent.getBrowser();
                    OperatingSystem os = userAgent.getOperatingSystem();
                    Version version = browser.getVersion(Agent);
                    String info = browser.getName() + "/" + version.getVersion();
                    log.setOs(os.getName());
                    log.setOsversion(info);
                }catch (Exception e){}
                log.setAddress(request.getRequestURL().toString());
                log.setMode(request.getMethod());
                log.setCreatetime(LocalDateTime.now());
                iLogService.save(log);
            }

            if(result.isSuccess()){
               // System.out.println("通过拦截器");
                return true;
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try{
            JSONObject json = new JSONObject();
            json.put("success","false");
            //json.put("msg","认证失败，未通过拦截器");
            json.put("msg","未认证，请重新认证");
            json.put("code","10000");
            response.getWriter().append(json.toJSONString());
            //        response.getWriter().write("50000");
        }catch (Exception e){
            e.printStackTrace();
            response.sendError(500);
            return false;
        }

        return false;
    }

    /**
     * 获取客户端请求参数中所有的信息
     * @param request
     * @return
     */
    private Map<String, String> getAllRequestParam(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<String, String>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                //如果字段的值为空，判断若值为空，则删除这个字段>
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }
    public static String getIpAddr(HttpServletRequest request) {
        String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
        }

        return ip;
    }

    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
}
